﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using ArchiveLink;

namespace ArchiveLinkServiceHost
{
    using System.ServiceModel;

    public partial class ArchiveLinkServiceHost : ServiceBase
    {
        public ArchiveLinkServiceHost()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            StartSvc();
        }

        internal void StartSvc()
        {
            //EventLog.WriteEntry("Start Service");

            //Host = new ServiceHost(typeof(ArchiveLinkService.LinkerService));
            try
            {
                Linker = new Linker(new EventLogger(EventLog));
                Task.Factory.StartNew(StartWatcher);
            }
#if DEBUG
            catch (InvalidTimeZoneException ex)
#else
            catch (Exception ex)
#endif
            {
                EventLog.WriteEntry(ex.ToString());
                throw;
            }
            
        }

        private void StartWatcher()
        {
            try
            {
                Linker.StartDriveWatcher();
            }
#if DEBUG
            catch (InvalidTimeZoneException ex)
#else
            catch (Exception ex)
#endif
            {
                EventLog.WriteEntry(ex.ToString());
                throw;
            }
            
        }

        protected Linker Linker { get; set; }

        protected override void OnStop()
        {
        }
    }

    internal class EventLogger : ILogger
    {
        private readonly EventLog _eventLog;

        public EventLogger(EventLog eventLog)
        {
            _eventLog = eventLog;
        }

        public void WriteEntry(string message)
        {
            _eventLog.WriteEntry(message);
        }
    }
}
